<%@ page import="com.alibaba.fastjson.TypeReference" %>
<%@ page pageEncoding="UTF-8"%>
<%!
	static final String DEFAULT_SMS_SIGN = "天下布医";
	static final String SMS_DINGDONG_SINGLE_SEND_CODE_URL = "https://api.dingdongcloud.com/v1/sms/sendyzm";
	static final String SMS_DINGDONG_APIKEY = "d95cd3dc55425557f1aa48df0ff7cd69";

	// 生成6位数字验证码
	public static String getSix(){
        Random rad = new Random();
        String result  = rad.nextInt(1000000) +"";
        if(result.length() != 6){
            return getSix();
        }
        return result;
	}

	public static Message sendDingDongSmsSingleCode (String mobile, String content) {
		Message msg = new Message();
		try {
			content = URLEncoder.encode(content, "UTF-8");
			Map map = new HashMap();
			map.put("apikey", SMS_DINGDONG_APIKEY);
			map.put("mobile", mobile);
			map.put("content", content);
			String json = HttpUtil.post(SMS_DINGDONG_SINGLE_SEND_CODE_URL, map, "UTF-8", "");
			Map resultMap = JSONUtil.fromJson(json, new TypeReference<Map>(){});
			if (resultMap == null)
				return new Message(1001, "短信发送失败");
			Integer code = (Integer)resultMap.get("code");
			String codeMsg = Tools.getDesc(resultMap.get("msg"));
			if (code != 1) 
				msg.setErrcodeAndErrmsg(Tools.getInt(Tools.getDesc(code).replace(".0", "")), codeMsg);
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
			return new Message(1001, "短信发送失败");
		}
	}
	static final Integer REGISTER_SMS = 1;
	static final Integer BACKPWD_SMS = 2;
	static final Integer LOGIN_SMS = 3;
	static final Integer BIND_PHONE_SMS = 4;
	static final Integer VALI_PHONE_SMS = 5;
	static final Integer MODIFY_PWD_SMS = 6;
	static final Map<Integer, String> SMS_TEMPLATE_MAP = new HashMap<Integer, String>();
	static final Map<Integer, String> SMS_SIGN_MAP = new HashMap<Integer, String>();
	static {
		SMS_TEMPLATE_MAP.put(REGISTER_SMS, "【%s】验证码：%s，用于注册验证身份，千万不要告诉别人哦！");
		SMS_TEMPLATE_MAP.put(BACKPWD_SMS, "【%s】验证码：%s，用于找回密码，千万不要告诉别人哦！");
		SMS_TEMPLATE_MAP.put(LOGIN_SMS, "【%s】用于短信验证快捷登录");
		SMS_TEMPLATE_MAP.put(BIND_PHONE_SMS, "【%s】验证码：%s，用于绑定手机号，千万不要告诉别人哦！");
		SMS_TEMPLATE_MAP.put(VALI_PHONE_SMS, "【%s】验证码：%s，用于更换手机号验证身份，千万不要告诉别人哦！");
		SMS_TEMPLATE_MAP.put(MODIFY_PWD_SMS, "【%s】验证码：%s，用于修改密码验证身份，千万不要告诉别人哦！");
		SMS_SIGN_MAP.put(999, "天下专家");
	}


	// 发送验证码
	public Message pushSms(String phone, Integer category, Integer hospital, Input input) {
		Message msg = new Message();
		if (!isChinaPhoneLegal(phone)) {
			return new Message(1002, "手机号不合法");
		}
		List<Map> list = QBuilder.db("basedb").select().from("sms_record").where(new Where("hospital=", hospital).and("phone=", phone).and("category=", category).and("status=", STATUS_ENABLE)).order("create_time", "desc").page(1, 1).query().getResultObj();
		if (!isEmpty(list)) {
			Map recordMap = list.get(0);
			Integer expirein = (Integer)recordMap.get("expire_in");
			Long now = System.currentTimeMillis();
			Long smsValidTime = Tools.getLong(recordMap.get("create_time") + "") + expirein * 1000;
			if (now < smsValidTime)
				return new Message(1003, "您的请求过于频繁，请稍后重试");
		}
		String code = getSix();
		if (SMS_TEMPLATE_MAP.get(category) == null)
			 return new Message(1002, "非法请求");
		String purpose = Tools.getDesc(SMS_TEMPLATE_MAP.get(category));
		String smsSign = Tools.getDesc(SMS_SIGN_MAP.get(hospital), DEFAULT_SMS_SIGN);
		String content = String.format(purpose, new Object[]{smsSign, code});
		Message sendMsg = sendDingDongSmsSingleCode(phone, content);
		if (sendMsg.getErrcode() != 0)
			return new Message(1001, "验证码发送失败，请重试");
		else {
			// 发送成功
			Map smsMap = new HashMap();
			smsMap.put("phone", phone);
			smsMap.put("code", code);
			smsMap.put("content", content);
			smsMap.put("useragent", Tools.getDesc(input.getUseragent(), ""));
			smsMap.put("ipv4", input.getIp());
			smsMap.put("type", 0);
			smsMap.put("category", category);
			smsMap.put("purpose", purpose);
			smsMap.put("create_time", System.currentTimeMillis());
			smsMap.put("expire_in", 60);
			smsMap.put("valid_in", 300);
			smsMap.put("hospital", hospital);
			smsMap.put("status", STATUS_ENABLE);
			smsMap.put("is_used", 0);
			smsMap.put("json", "{}");
			DBTools.db("basedb").addItem("sms_record", smsMap);
		}
		return msg;
	}

	// 验证码是否有效或过期
	public Message validateSms(String phone, String code, Integer category, Integer hospital) {
		if (!isChinaPhoneLegal(phone)) {
			return new Message(1002, "手机号不合法");
		}
		Message msg = new Message(0, "验证通过");
		List<Map> list = QBuilder.db("basedb").select().from("sms_record").where(new Where("hospital=", hospital).and("phone=", phone).and("category=", category).and("status=", STATUS_ENABLE).and("is_used=", 0)).order("create_time", "desc").page(1, 1).query().getResultObj();
		if (isEmpty(list))
			return new Message(1004, "验证码无效，请重新发送");
		Map recordMap = list.get(0);
		Integer validIn = (Integer)recordMap.get("valid_in");
		Long now = System.currentTimeMillis();
		Long smsValidTime = Tools.getLong(recordMap.get("create_time") + "") + validIn * 1000;
		if (now > smsValidTime)
			return new Message(1005, "验证码无效，请重新发送");
		String codeDisk = Tools.getDesc(recordMap.get("code"));
		if (!codeDisk.equals(code))
			return new Message(1006, "验证码不正确，请重新输入");
		else {
			// 0未使用  1已使用
			recordMap.put("is_used", 1);
			DBTools.db("basedb").modItem("sms_record", recordMap);
		}
		return msg;
	}
%>
